package com.hft.utils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class BaseUtils {

    /**
     * 模拟浏览器请求，获取验证url的连通性，http状态为200，返回true
     * @param urlStr
     * @return
     */
    public static boolean isAccessableUrl(String urlStr) {
        try {
            URL url = new URL(BaseUtils.addProtocolHeader(urlStr));
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
            httpConnection.addRequestProperty("Accept-Language", "zh-cn");
            httpConnection.addRequestProperty("Content-type", "text/plain; charset=utf-8");
            httpConnection.addRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows; U; Windows NT 5.2) Gecko/2008070208 Firefox/3.0.1");
            httpConnection.setConnectTimeout(4000);
            int responseCode = httpConnection.getResponseCode();
            System.out.println("responseCode=" + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 若url无主机头，则为其添加http主机头
     */
    public static String addProtocolHeader(String url) {
        if (url.startsWith(Constants.PROTOCOL_HTTP)||url.startsWith(Constants.PROTOCOL_HTTPS)||url.startsWith(Constants.PROTOCOL_FILE)||url.startsWith(Constants.PROTOCOL_FTP)) {
            return url;
        }
        return Constants.PROTOCOL_HTTP + url;
    }

}
